import React, { PureComponent } from 'react'
import { Link, withRouter } from 'react-router-dom'
import { Menu } from 'antd';
import { connect } from 'react-redux';

import logo from '../../assets/images/logo.png'
import { menulist } from '../../assets/data/menulist'
import { setHeadTitle } from '../../redux/actions'
import './index.scss'

const { SubMenu } = Menu;
class LeftNav extends PureComponent {
  state = {
    openKeys: [],//初始展开的 SubMenu 菜单项 key 数组
  };

  componentDidMount() {
    // console.log(this);
    // this.selectedItem();
  }

  /*
  判断当前登陆用户对item是否有权限
   */
  hasAuth = (item) => {
    const { key, isPublic } = item

    const menus = this.props.user.role.menus
    const username = this.props.user.username
    /*
    1. 如果当前用户是admin
    2. 如果当前item是公开的
    3. 当前用户有此item的权限: key有没有menus中
     */
    if (username === 'admin' || isPublic || menus.indexOf(key) !== -1) {
      return true
    } else if (item.children) { // 4. 如果当前用户有此item的某个子item的权限
      return !!item.children.find(child => menus.indexOf(child.key) !== -1)
    }

    return false
  }

  // 回显选中的项
  /* selectedItem() {
    // this.props.location.pathname
    let openKeys = [];
    menulist.forEach(item => {
      if (item.key === this.props.location.pathname) {
        openKeys.push(item.key);
      } else {
        item.children && item.children.forEach(item1 => {
          if (item1.key === this.props.location.pathname) {
            openKeys.push(item.key);
          }
        });
      }
    });
    this.setState({
      openKeys,
    });
  } */

  // 点击跳转路由
  handleMenuItem = (v) => {
    // console.log('key: ', key,this);
    this.props.setHeadTitle(v.title);
    this.props.history.push(v.key);
  }
  /* handleMenu = (openKeys) => {
    // console.log('openKeys: ', openKeys);
    let openKeys1=openKeys.length >= 2 ? [openKeys[openKeys.length - 1]] : openKeys;
    if(openKeys1[0].indexOf("/product")===0){
      openKeys1=["/product"];
    }
    this.setState({ openKeys:openKeys1});
  } */
  recursionMenuItem = (values) => {
    // 查找一个与当前请求路径匹配的子Item
    const path = this.props.location.pathname;
    // console.log('values: ', values,path);
    const cItem = values.children.find(cItem => path.indexOf(cItem.key) === 0);
    // console.log('cItem: ', cItem);
    // 如果存在, 说明当前item的子列表需要打开
    if (cItem) {
      this.props.setHeadTitle(cItem.title);
      this.openKey = values.key;
    }
    return <SubMenu key={values.key} icon={values.icon} title={values.title}>
      {
        values.children.map(m => {
          return !m.children ? <Menu.Item key={m.key} icon={m.icon} onClick={() => this.handleMenuItem(m)}>{m.title}</Menu.Item> : this.recursionMenuItem(m)
        })
      }
    </SubMenu>
  }
  renderItem = (v) => {
    // console.log('v: ', v);
    // 得到当前请求的路由路径
    const path = this.props.location.pathname;
    // 判断item是否是当前对应的item
    if (v.key === path || path.indexOf(v.key) === 0) {
      // 更新redux中的headerTitle状态
      this.props.setHeadTitle(v.title)
    }
    return (<Menu.Item key={v.key} icon={v.icon} onClick={() => this.handleMenuItem(v)}>
      {v.title}
    </Menu.Item>)
  }
  renderMenuItem = () => {
    // console.log(menulist);
    return menulist.map(v => {
      if (this.hasAuth(v)) {
        return !v.children ? this.renderItem(v) : this.recursionMenuItem(v)
      } else {
        return []
      }
    })

  }
  /* renderReduce = () => {
    return menulist.reduce((pre, v) => {
      if (!v.children) {
        pre.push(<Menu.Item key={v.key} icon={v.icon} onClick={() => this.handleMenuItem(v.key)}>
          {v.title}
        </Menu.Item>)
      } else {
        pre.push(this.recursionMenuItem(v))
      }
      return pre;
    }, [])
  } */

  /*
  在第一次render()之前执行一次
  为第一个render()准备数据(必须同步的)
   */
  UNSAFE_componentWillMount() {
    this.menuNodes = this.renderMenuItem();
    // console.log(this.menuNodes);
  }

  render() {
    // 得到需要打开菜单项的key
    const openKey = this.openKey;
    let path = this.props.location.pathname;
    if (path.indexOf("/product") === 0) {
      path = "/product";
    }
    return (
      <div className="left-nav">
        <Link to="/home" className="left-nav-header flex-ac">
          <img src={logo} alt="导航栏图片" />
          <h1>React 后台</h1>
        </Link>
        <Menu
          mode="inline"
          theme="dark"
          selectedKeys={[path]}
          defaultOpenKeys={[openKey]}
        >
          {this.menuNodes}
          {/* <Menu.Item key="1" icon={<HomeFilled />}>
            首页
          </Menu.Item>
          <SubMenu key="sub1" icon={<DesktopOutlined />} title="商品">
            <Menu.Item key="13" icon={<PieChartOutlined />}>品类管理</Menu.Item>
            <Menu.Item key="14" icon={<PieChartOutlined />}>商品管理</Menu.Item>
          </SubMenu>
          <Menu.Item key="3" icon={<ContainerOutlined />}>
            用户管理
          </Menu.Item>
          <Menu.Item key="4" icon={<ContainerOutlined />}>
            角色管理
          </Menu.Item>
          <SubMenu key="sub2" icon={<AppstoreOutlined />} title="图形图表">
            <Menu.Item key="9">Option 9</Menu.Item>
            <Menu.Item key="10">Option 10</Menu.Item>
            <SubMenu key="sub3" title="Submenu">
              <Menu.Item key="11">Option 11</Menu.Item>
              <Menu.Item key="12">Option 12</Menu.Item>
            </SubMenu>
          </SubMenu> */}
        </Menu>
      </div>
    )
  }
}

export default connect(
  state => ({ user: state.user }),
  { setHeadTitle }
)(withRouter(LeftNav))